package com.hoshiicloud.market.controller.market;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.market.entity.market.Marketing;
import com.hoshiicloud.market.param.market.MarketingAddParam;
import com.hoshiicloud.market.param.market.MarketingQueryParam;
import com.hoshiicloud.market.param.market.MarketingUpdateParam;
import com.hoshiicloud.market.service.market.MarketingService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 营销活动 控制器
 * </p>
 *
 * @author campchen
 * @since 2019-05-14
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/marketing")
@Api(value = "营销服务", tags = {"营销活动管理"})
public class MarketingController {
    @Autowired
    private MarketingService marketingService;

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 分页查询营销活动
    */
    @ApiOperation(value = "分页查询营销活动")
    @PostMapping("/query/page")
    public Response page(@RequestBody @Valid MarketingQueryParam param) {
        try {
            log.info("分页查询营销活动");
            QueryWrapper<Marketing> queryWrapper = new QueryWrapper<Marketing>();
            queryWrapper.eq(param.getCompanyid() != null, "companyid", param.getCompanyid());
            queryWrapper.eq(param.getPlatformid() != null, "platformid", param.getPlatformid());
            queryWrapper.eq(param.getStoreid() != null, "storeid", param.getStoreid());
            queryWrapper.eq(StringUtils.isNotBlank(param.getCode()), "code", param.getCode());
            queryWrapper.eq(StringUtils.isNotBlank(param.getName()), "name", param.getName());
            queryWrapper.eq(param.getType() != null, "type", param.getType());
            queryWrapper.eq(param.getEventStart() != null, "event_start", param.getEventStart());
            queryWrapper.eq(param.getEventEnd() != null, "event_end", param.getEventEnd());
            queryWrapper.eq(param.getBuying() != null, "buying", param.getBuying());
            queryWrapper.eq(param.getBuyingTimeform() != null, "buying_timeform", param.getBuyingTimeform());
            queryWrapper.eq(param.getBuyingTimeend() != null, "buying_timeend", param.getBuyingTimeend());
            queryWrapper.eq(param.getTotalLimits() != null, "total_limits", param.getTotalLimits());
            queryWrapper.eq(param.getSexLimits() != null, "sex_limits", param.getSexLimits());
            queryWrapper.eq(param.getAgesFrom() != null, "ages_from", param.getAgesFrom());
            queryWrapper.eq(param.getAgesTo() != null, "ages_to", param.getAgesTo());
            queryWrapper.eq(param.getMemberLevel() != null, "member_level", param.getMemberLevel());
            queryWrapper.eq(param.getZone() != null, "zone", param.getZone());
            queryWrapper.eq(param.getFullAmount() != null, "full_amount", param.getFullAmount());
            queryWrapper.eq(param.getRewardPoints() != null, "reward_points", param.getRewardPoints());
            queryWrapper.eq(param.getRewardCoupon() != null, "reward_coupon", param.getRewardCoupon());
            queryWrapper.eq(param.getCouponPrice() != null, "coupon_price", param.getCouponPrice());
            queryWrapper.eq(param.getStatus() != null, "status", param.getStatus());
            queryWrapper.eq(param.getDeleted() != null, "deleted", param.getDeleted());
            IPage<Marketing> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            queryWrapper.select(BeanUtils.getSqlSelect(Marketing.class));
            return Response.data(marketingService.page(page, queryWrapper));
          } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
          } catch (Exception e) {
            log.error("分页查询营销活动异常", e);
            return Response.failed("分页查询营销活动异常");
        }
    }
    /**
    * @param id
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 根据id查询营销活动
    */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询营销活动")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(marketingService.getById(id));
    }

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 新增
    */
    @PostMapping("/save")
    @ApiOperation(value = "新增营销活动")
    public Response save(@RequestBody @Valid MarketingAddParam param) {
        try {
            /*
             * 此段为判断添加人属于哪个机构，且限制其添加信息区域
             * */
            Marketing data = BeanUtils.covertType(param, Marketing.class);
            return Response.data(marketingService.save(data));
        } catch (ServiceException e) {
            log.error("新增营销活动异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("新增营销活动异常", e);
            return Response.failed();
        }
    }

    /**
    * @param param
    * @return com.hoshiicloud.common.rpc.Response
    * @description: 修改营销活动
    */
    @PutMapping("/update")
    @ApiOperation(value = "修改营销活动")
    public Response update(@RequestBody @Valid MarketingUpdateParam param) {
        try {
            Marketing data = BeanUtils.covertType(param, Marketing.class);
            return Response.data(marketingService.updateById(data));
        }catch (ServiceException e) {
            log.error("修改营销活动异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("修改营销活动异常", e);
            return Response.failed();
        }
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除营销活动
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除营销活动")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        try {
            Marketing data=marketingService.getById(id);
            if(data==null){
                log.error("删除营销活动异常，无法找到营销活动记录");
                return Response.failed("删除营销活动异常，无法找到营销活动记录");
            }
            marketingService.deleteById(data);
            return Response.success("删除营销活动成功");
        }catch (ServiceException e) {
            log.error("删除营销活动异常", e);
            return Response.failed(e.getError().getMsg());
        }catch (Exception e) {
            log.error("删除营销活动异常", e);
            return Response.failed();
        }
    }

}
